﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace CY_MVC.Core
{
    internal static class ScriptHelper
    {
        private const string ScriptManagerItemsKey = "CY_MVC.HtmlParser.ScriptHelper";

        internal static void Add(string p_Script)
        {
            if (HttpContext.Current.Items[ScriptManagerItemsKey] == null)
            {
                HttpContext.Current.Items[ScriptManagerItemsKey] = new List<string>();
            }
            ((List<string>)HttpContext.Current.Items[ScriptManagerItemsKey]).Add(p_Script);
        }

        internal static string Generate(string p_ViewStr)
        {
            if (HttpContext.Current.Items.Contains(ScriptManagerItemsKey))
            {
                var ScriptList = ((List<string>)HttpContext.Current.Items[ScriptManagerItemsKey]);
                if (ScriptList != null)
                {
                    if (ScriptList.Count > 0)
                    {
                        var sb = new StringBuilder(200);
                        sb.Append("<script type=\"text/javascript\">");
                        foreach (var item in ScriptList)
                        {
                            sb.Append(item + Environment.NewLine);
                        }
                        sb.Append("</script></body>");
                        return p_ViewStr.Replace("</body>", sb.ToString());
                    }
                }
            }
            return p_ViewStr;
        }
    }
}
